package it.univaq.di.helpdesk.common.utils;

import it.univaq.di.helpdesk.business.common.HelpDeskServiceFactory;
import it.univaq.di.helpdesk.business.common.UserService;
import it.univaq.di.helpdesk.business.errors.BusinessException;
import it.univaq.di.helpdesk.business.model.Menu;
import it.univaq.di.helpdesk.business.model.Role;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MenuManager {
	private static Map<String, List<Menu>> roleMenuMap = null;
	
	private MenuManager() {}
	
	public synchronized static void loadMenu() throws BusinessException {
		if (roleMenuMap == null) {
			HelpDeskServiceFactory factory = HelpDeskServiceFactory.getInstance();
			UserService service = factory.getUserService();

			List<Role> rolesMenu = service.findAllRoles();
			
			roleMenuMap = new HashMap<String, List<Menu>>();
			for (Role role : rolesMenu) {
				roleMenuMap.put(role.getName(), role.getMenu());
			}
		}
	}
	
	public static List<Menu> getUserMenu(Set<Role> roles) {
		List<Menu> userMenu = new ArrayList<Menu>();
		for (Role role : roles) {
			for (Menu menu :  roleMenuMap.get(role.getName())) {
				userMenu.add(menu);
			}
		}
		return userMenu;
	}	
}
